
import { useState } from 'react';
import { getValidateMsg } from '@/utils'
import { ValidateType } from '@/types'
import { request } from '@/request'

interface RegisterFields {
    username: string;
    phone: string;
    password: string;
    confirmPassword: string;
};

type FormErrors = {
    [K in keyof RegisterFields]?: string;
}

const initValue = {
    username: '',
    phone: '',
    password: '',
    confirmPassword: '',
}

const useRegister = () => {
    const [isFirstSubmit, setIsFirstSubmit] = useState(true);
    const [values, setValues] = useState<RegisterFields>(initValue);
    const [errors, setErrors] = useState<FormErrors>({});

    const handleChange = (fieldName: keyof RegisterFields) => (event: React.ChangeEvent<HTMLInputElement>) => {
        const fieldValue = event.target.value;
        setValues({
            ...values,
            [fieldName]: fieldValue,
        });
        validate()
    };

    const validate = () => {
        const newErrors: FormErrors = { ...errors };
        newErrors.username = getValidateMsg(ValidateType.username, [values.username]);
        newErrors.phone = getValidateMsg(ValidateType.phone, [values.phone]);
        newErrors.password = getValidateMsg(ValidateType.password, [values.password]);
        newErrors.confirmPassword = getValidateMsg(ValidateType.confirmPassword, [values.password, values.confirmPassword]);
        setErrors(newErrors);

        return newErrors
    }

    // 处理表单的提交
    const handleSubmit = async () => {
        const newErrors = validate()
        if (isFirstSubmit) {
            setIsFirstSubmit(false)
        }

        if (Object.values(newErrors).filter(msg => msg !== '').length === 0) {
            request('/auth/register', {
                method: 'POST',
                data: {
                    username: values.username,
                    phone: values.phone,
                    password: values.password
                },
                showSuccess: true,
                success: () => {
                    setValues(initValue)
                }
            })
        }
    };


    return {
        values,
        isFirstSubmit,
        handleSubmit,
        handleChange,
        errors
    }
}

export default useRegister;